<?php
/**
 * @name /www/itemsearch-widget-ajax.php
 * @author Michael Foss <michael@mikefoss.com>
 * @version 2011.04.02
 *
 * Provides ajax functionality for the item search widget
 * in /lib/private/ItemSearchWidget.php.
 */

 // Sets up configuration settings and includes libraries.
require_once('_ini.php');
ReqLib('/lib/private/Item.php');
ReqLib('/lib/private/User.php');

/**
 * Sends back ajax data.
 *
 * Because this file provides server-side functionality only,
 * it should only ever need this function.
 */
function DefinePreload() {
  // Provide JSON formatted feedback
  header('content-type: application/json');

  // Get query
  $query = $_POST['term'];

  // Get tags
  $tags = $_POST['tags'];
  if ($tags)
    $tags = explode('|', $tags);
  else
    $tags = array();

  // Get IsVerified modifier
  $user = new User();
  $user->Load($_SESSION['userId']);
  if ($user->HasRole('administrator') && isset($_POST['v']))
    switch ($_POST['v']) {
      case 'B':
        $isVerified = -1;
        break;
      case 'N':
        $isVerified = false;
        break;
      default:
        $isVerified = true;
        break;
    }
  else
    $isVerified = true;

  // Do the search
  $items = Item::FilteredSearch(
    $query,
    $tags,
    $isVerified
  );

  // Return the search results in JSON format
  $itemNames = array();
  for ($i = 0; $i < count($items); $i++)
    $itemNames[] = $items[$i]->Name;
  print(json_encode($itemNames));
  die();
}

// Launches the page; without this, nothing happens.
require_once('_loader.php');